package com.ibeeking.found.msg.rest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ibeeking.found.common.entity.DictDTO;
import com.ibeeking.found.common.enums.DefaultEnum;
import com.ibeeking.found.common.enums.DictTypeEnum;
import com.ibeeking.found.common.enums.PublishStatusEnum;
import com.ibeeking.found.common.utils.UserUtils;

import com.ibeeking.gmc.global.api.feign.GlobalDictFeignClient;
import com.ibeeking.found.msg.rest.service.ISmsConfigSignService;
import com.ibeeking.found.msg.service.common.bo.SmsConfigSignBO;

import com.ibeeking.found.msg.service.common.dos.SmsConfigSignDO;
import com.ibeeking.found.msg.service.common.param.SmsConfigSignParam;
import com.ibeeking.found.msg.service.common.query.SmsConfigSignQuery;
import com.ibeeking.found.msg.service.common.vo.SmsConfigSignVO;
import com.ibeeking.found.msg.service.mapper.SmsConfigSignMapper;
import com.ibeeking.nematos.core.utils.SpringBeanUtil;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.data.StringUtils;
import com.ibeeking.nematos.utils.json.JsonUtils;
import com.ibeeking.nematos.utils.result.ResponseResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
 * @ClassName SmsConfigSignServiceImpl
 * @Description
 * @Author ibeeking
 * @Date 2021-06-09 15:57
 **/
@Service
public class SmsConfigSignServiceImpl  extends ServiceImpl<SmsConfigSignMapper, SmsConfigSignDO> implements ISmsConfigSignService {

    @Resource
    private SmsConfigSignMapper SmsConfigSignMapper;

    @Resource
    private GlobalDictFeignClient globalDictFeignClient;

    @Override
    public List<SmsConfigSignVO> list(SmsConfigSignQuery query){
        List<SmsConfigSignDO> SmsConfigSignDOs = SmsConfigSignMapper.selectList(new LambdaQueryWrapper<SmsConfigSignDO>()
                .eq(query.getId() != null, SmsConfigSignDO::getId, query.getId())
                .eq(query.getConfigId() != null, SmsConfigSignDO::getConfigId, query.getConfigId())
                .eq(query.getHaveDefault() != null, SmsConfigSignDO::getHaveDefault, query.getHaveDefault())
                .eq(query.getPublishStatus() != null, SmsConfigSignDO::getPublishStatus, query.getPublishStatus())
                .eq(StringUtils.isNotEmpty(query.getSignName()), SmsConfigSignDO::getSignName, query.getSignName())
                .eq(StringUtils.isNotEmpty(query.getSmsVendorCode()), SmsConfigSignDO::getSmsVendorCode, query.getSmsVendorCode())
        );
        List<SmsConfigSignVO>  SmsConfigSignVOS = JsonUtils.jsonToList(SmsConfigSignDOs, SmsConfigSignVO.class);
        List<SmsConfigSignVO> result = new ArrayList<>();
        if (Collections3.isNotEmpty(SmsConfigSignVOS)){
            Map<String, String> smsVendorMap = getSmsVendorDictNames();
            result = SmsConfigSignVOS.stream().map(c -> {
                SmsConfigSignVO SmsConfigSignVO = BeanUtil.convertBean(c, SmsConfigSignVO.class);
                SmsConfigSignVO.setSmsVendorName(smsVendorMap.get(c.getSmsVendorCode()));
                SmsConfigSignVO.setPublishStatusDesc(PublishStatusEnum.getName(c.getPublishStatus()));
                return SmsConfigSignVO;
            }).collect(Collectors.toList());
        }
        return result;
    }

    @Override
    public List<SmsConfigSignVO> listAll(){
        List<SmsConfigSignDO> SmsConfigSignDOs = SmsConfigSignMapper.selectList(new LambdaQueryWrapper<SmsConfigSignDO>());
        List<SmsConfigSignVO>  SmsConfigSignVOS = JsonUtils.jsonToList(SmsConfigSignDOs, SmsConfigSignVO.class);
        List<SmsConfigSignVO> result = new ArrayList<>();
        if (Collections3.isNotEmpty(SmsConfigSignVOS)){
            Map<String, String> smsVendorMap = getSmsVendorDictNames();
            result = SmsConfigSignVOS.stream().map(c -> {
                SmsConfigSignVO SmsConfigSignVO = BeanUtil.convertBean(c, SmsConfigSignVO.class);
                SmsConfigSignVO.setSmsVendorName(smsVendorMap.get(c.getSmsVendorCode()));
                SmsConfigSignVO.setPublishStatusDesc(PublishStatusEnum.getName(c.getPublishStatus()));
                return SmsConfigSignVO;
            }).collect(Collectors.toList());
        }
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean add(SmsConfigSignParam param)  {
        if (!checkUnique (param)){
            throw new BusinessException("该名称已存在，无需新增!");
        }
        SmsConfigSignDO SmsConfigSignDO = BeanUtil.convertBean(param, SmsConfigSignDO.class);
        SmsConfigSignDO.setCreateBy(UserUtils.getUserId());
        SmsConfigSignDO.setCreateTime(LocalDateTime.now());
        SmsConfigSignDO.setModifyTime(LocalDateTime.now());
        int insertRows = SmsConfigSignMapper.insert(SmsConfigSignDO);

        return insertRows > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean modify(SmsConfigSignParam param){
        Long userId = UserUtils.getUserId();
        SmsConfigSignDO smsConfigSignDO = BeanUtil.convertBean(param, SmsConfigSignDO.class);
        smsConfigSignDO.setModifyBy(userId);
        smsConfigSignDO.setModifyTime(LocalDateTime.now());
        return SmsConfigSignMapper.updateById(smsConfigSignDO)>0;
    }

    @Override
    public SmsConfigSignVO view(Long id){
        SmsConfigSignDO smsConfigSignDO = SmsConfigSignMapper.selectById(id);
        SmsConfigSignVO smsConfigSignVO = BeanUtil.convertBean(smsConfigSignDO, SmsConfigSignVO.class);
        if(smsConfigSignVO != null){
            Map<String, String> smsVendorMap = getSmsVendorDictNames();
            smsConfigSignVO.setSmsVendorName(smsVendorMap.get(smsConfigSignVO.getSmsVendorCode()));
            smsConfigSignVO.setPublishStatusDesc(PublishStatusEnum.getName(smsConfigSignVO.getPublishStatus()));
        }
        return smsConfigSignVO;
    }

    @Override
    public SmsConfigSignBO queryById(Long id){
        SmsConfigSignDO smsConfigSignDO = SmsConfigSignMapper.selectById(id);
        SmsConfigSignBO smsConfigSignBO = BeanUtil.convertBean(smsConfigSignDO, SmsConfigSignBO.class);
        return smsConfigSignBO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean changeDefaultStatus(Long id,Integer status){
        Long userId = UserUtils.getUserId();

        if(status == DefaultEnum.YES.getValue()) {
            SmsConfigSignQuery query = new SmsConfigSignQuery();
            query.setPublishStatus(status);
            List<SmsConfigSignDO> smsConfigSignDOS = SmsConfigSignMapper.selectList(new LambdaQueryWrapper<SmsConfigSignDO>().eq(SmsConfigSignDO::getHaveDefault,status));
            if(Collections3.isNotEmpty(smsConfigSignDOS)){
                SmsConfigSignDO otherSmsConfigSignDO = smsConfigSignDOS.get(0);
                if(otherSmsConfigSignDO.getId() != id){
                    otherSmsConfigSignDO.setHaveDefault(DefaultEnum.NO.getValue());
                    otherSmsConfigSignDO.setModifyBy(userId);
                    otherSmsConfigSignDO.setModifyTime(LocalDateTime.now());
                    SmsConfigSignMapper.updateById(otherSmsConfigSignDO);
                }
            }
        }
        SmsConfigSignDO smsConfigSignDO = SmsConfigSignMapper.selectById(id);
        if(smsConfigSignDO == null){
            throw new BusinessException("没有找到相关记录");
        }
        smsConfigSignDO.setHaveDefault(status);
        smsConfigSignDO.setPublishStatus(PublishStatusEnum.ENABLE.getValue());
        smsConfigSignDO.setModifyBy(userId);
        smsConfigSignDO.setModifyTime(LocalDateTime.now());
        return SmsConfigSignMapper.updateById(smsConfigSignDO) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean changePusblishStatus(Long id,Integer status){
        SmsConfigSignDO smsConfigSignDO = SmsConfigSignMapper.selectById(id);
        if(smsConfigSignDO == null){
            throw new BusinessException("记录不存在");
        }
        smsConfigSignDO.setPublishStatus(status);
        smsConfigSignDO.setModifyBy(UserUtils.getUserId());
        smsConfigSignDO.setModifyTime(LocalDateTime.now());
        return SmsConfigSignMapper.updateById(smsConfigSignDO)>0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean del(Long id){
        SmsConfigSignDO smsConfigSignDO = SmsConfigSignMapper.selectById(id);
        if(smsConfigSignDO == null){
            throw new BusinessException("记录不存在");
        }
        return SmsConfigSignMapper.deleteById(id)>0;
    }

    private Boolean checkUnique (SmsConfigSignParam param){
        LambdaQueryWrapper<SmsConfigSignDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SmsConfigSignDO::getSignName, param.getSignName());
        wrapper.eq(SmsConfigSignDO::getConfigId, param.getConfigId());
        List<SmsConfigSignDO> dos =  SmsConfigSignMapper.selectList(wrapper);
        return Collections3.isEmpty(dos);
    }

    private Map<String, String> getSmsVendorDictNames() {
        ResponseResult<List<DictDTO>> responseResult =  globalDictFeignClient.queryDictByType(DictTypeEnum.MSG_SMS_VENDOR.getValue());
        if (responseResult == null) return Collections3.emptyMap();
        List<DictDTO> dictDTOS =  responseResult.getData();
        if (Collections3.isEmpty(dictDTOS)) return Collections3.emptyMap();
        Map<String, String> dictDTOSMaps =  dictDTOS.stream().collect(Collectors.toMap(DictDTO::getValue, DictDTO::getLabel, (key1, key2) -> key2));
        return dictDTOSMaps;
    }
    private SmsConfigSignServiceImpl getBean() {
        return SpringBeanUtil.getBean(this.getClass());
    }

}
